package peer.p2pnet.message;

import java.net.DatagramPacket;

import peer.Message;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;
import peer.tools.Mdb;

public class PubAddMessage extends Message{
	public short sType=peer.tools.MessageType.sType_PubAddMessage;
	int sessionId =0;
	byte[] dpData=null;
	byte[] md=null;
	Mdb mdb;
	byte[] nameByte;
	short nameLength;
	String name;
	int sourceSessionId;
	public PubAddMessage (byte[] md,String name){
		this.md=md;
		this.name=name;
		mdb=new Mdb(md);
		this.sourceSessionId=peer.Config.sourceSessionIdMange.getSessionId(mdb);
		nameByte=name.getBytes();
		nameLength=(short) nameByte.length;
		dpData=new byte[10+16+4+nameByte.length];
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		ByteIntSwitch.toByteArray(sessionId, dpData, 4);  //add: sessionId
		System.arraycopy(md, 0, dpData, 8,16);
		ByteShortSwitch.toByteArray(nameLength, dpData, 8+16);  //add: name length
		System.arraycopy(nameByte,0,dpData,8+16+2,nameByte.length);
		ByteIntSwitch.toByteArray(sourceSessionId, dpData, 8+16+2+nameByte.length);  //add: sourceSessionId
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public int getSourceSessionId(){
		return sourceSessionId;
	}
	
	public void setSessionId(int sessionId){
		this.sessionId=sessionId;
		ByteIntSwitch.toByteArray(this.sessionId, dpData, 4);  //add: sessionId
	}
	
	public int getSessionId (){
		return sessionId ;
	}
	
	public byte[] getMd(){
		return md;
	}
	
	public String getName(){
		return name;
	}
	
	public PubAddMessage(DatagramPacket dp){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		sessionId=ByteIntSwitch.toInt(dpData, 4);
		md=new byte[16];
		System.arraycopy(dpData, 8, md, 0, 16);
		nameLength=ByteShortSwitch.toShort(dpData, 8+16);
		nameByte=new byte[nameLength];
		System.arraycopy(dpData,8+16+2,nameByte,0,nameLength);
		name=new String(nameByte);
		sourceSessionId=ByteIntSwitch.toInt(dpData, 8+16+2+nameLength);
	}
}
